<?php
namespace app\admin\controller;
use app\admin\controller\base\BaseController;
use app\admin\model\AuthAccess;
use app\admin\model\Authrole;
use think\Loader;
use think\Request;

/**
 * 后台角色控制器
 * Class AuthroleController
 * @package app\admin\controller
 */
class AuthroleController extends BaseController {
    /**
     * 权限授予
     * @param Request $request
     * @return mixed
     */
    public function access(Request $request){
        if ($request->isPost()){
            $post_data = $request->post();
            $model = Loader::model('Authrole');
            $res = $model->updateData($post_data);
            if ($res !== false){
                $this->success('分配权限成功！',url('index'));
            }else{
                $this->error('分配权限失败！'.$model->getError());
            }
        }else{
            $id = $request->param('id');
            $access = Authrole::where('id',$id)->value('access');
            $list = AuthAccess::where(['level'=>['<=',3]])->field('id,name,pid')->select();
            $access = explode(',',$access);
            foreach ($list as $key => $value){
                if (in_array($value['id'],$access)){
                    $list[$key]['checked'] = true;
                }
            }
            $tree = array_to_tree($list);

            $this->assign('id',$id);
            $this->assign('tree',$tree);
            return $this->fetch();
        }
    }
}